package com.dsg.service.apply.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dsg.common.util.UUIDGenerator;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.dao.apply.DsgApplyCusMapper;
import com.dsg.entity.apply.*;
import com.dsg.entity.dto.ApplyList;
import com.dsg.entity.dto.CusResultDto;
import com.dsg.entity.dto.CusSearchDto;
import com.dsg.entity.dto.CusSumDto;
import com.dsg.entity.system.DsgSysParameter;
import com.dsg.service.DsgServiceImpl;
import com.dsg.service.apply.*;
import com.dsg.service.set.IDsgSetCusBacklistService;
import com.dsg.service.system.IDsgSysParameterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 個人申請資料 服务实现类
 * </p>
 *
 * @author system
 * @since 2020-07-04
 */
@Service
public class DsgApplyCusServiceImpl extends DsgServiceImpl<DsgApplyCusMapper, DsgApplyCus> implements IDsgApplyCusService {
    @Autowired
    IDsgApplyComService comService;
    @Autowired
    IDsgSetCusBacklistService cusBacklistService;
    @Autowired
    IDsgApplyResultService resultService;
    @Autowired
    IDsgSysParameterService parameterService;
    @Autowired
    IDsgApplyStatusService statusService;
    @Autowired
    IDsgApplyBillService billService;

    public Page<ApplyList> applyList(Page<ApplyList> page, Integer appType, String appNo, Integer appStatus, String carNo, String cusNo, String entCode, Integer keepType) {
        return baseMapper.applyList(page, appType, appNo, appStatus, carNo, cusNo, entCode, keepType);
    }

    public String getOwnsIdByCusNo(String cusNo) {
        return baseMapper.getOwnsIdByCusNo(cusNo);
    }

    public CusSumDto selectCus(String cusNo) {
        CusSumDto dto = baseMapper.selectCus(cusNo);
        String cusType = dto.getCusType();
        if (StringUtil.isNotEmpty(cusType)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("PARA_TYPE", "CUS_TYPE");
            List<DsgSysParameter> parameters = parameterService.list(wrapper);
            String[] cusTypes = cusType.split(",");
            String cusTypeName = "";
            for (int i = 0; i < cusTypes.length; i++) {
                String cusKey = cusTypes[i];
                DsgSysParameter parameter = parameters.stream().filter(e -> e.getParaKey().equals(cusKey)).findFirst().get();
                String cusName = parameter.getParaValue();
                if (StringUtil.isEmpty(cusTypeName)) {
                    cusTypeName = cusName;
                } else {
                    cusTypeName += "," + cusTypeName;
                }
            }
            dto.setCusType(cusTypeName);
        }
        return dto;
    }

    public List<CusResultDto> selectByKeepType(CusSearchDto dto) {
        return baseMapper.selectByKeepType(dto);
    }

    public List<CusResultDto> selectApplyCus(CusSearchDto dto) {
        return baseMapper.selectApplyCus(dto);
    }

    @Override
    public boolean audit(DsgApplyBill bill) {
        String mainNo = bill.getMainNo();
        String reason = null;
        String name = null;
        String cusId = null;
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("MAIN_NO", mainNo);
        wrapper.orderByDesc("CREATE_TIME");
        DsgApplyCus cus = getOne(wrapper, false);//同一個客有多份資料，取最新的那一份
        if (cus != null) {
            name = cus.getIdNo();
            wrapper = new QueryWrapper();
            wrapper.eq("ID_NO", cus.getIdNo());
            wrapper.ne("OID", cus.getOid());
            DsgApplyCus dupCus = getOne(wrapper, false);
            if (dupCus != null) {
                wrapper = new QueryWrapper();
                wrapper.eq("ID_CARD", cus.getIdNo());
                if (cusBacklistService.count(wrapper) > 0) {
                    reason = "黑名單";
                } else {
                    if (!cus.getEnName().equalsIgnoreCase(dupCus.getEnName())) {
                        reason = "ID相同，名字不同";
                    }
                }
            }
            if (reason == null) {
                //原來生效的資料改為失效
                LambdaUpdateWrapper<DsgApplyCus> updateWrapper = new LambdaUpdateWrapper();
                updateWrapper.eq(DsgApplyCus::getMainNo, bill.getMainNo());
                updateWrapper.eq(DsgApplyCus::getCusStatus, DsgApplyCus.CUS_STATUS_1);
                updateWrapper.set(DsgApplyCus::getCusStatus, DsgApplyCus.CUS_STATUS_3);
                update(new DsgApplyCus(), updateWrapper);

                cusId = cus.getOid();
                cus.setCusStatus(DsgApplyCus.CUS_STATUS_1);
                updateById(cus);
            }
        } else {
            DsgApplyCom com = comService.getOne(wrapper, false);
            if (com != null) {
                name = com.getComBrcNo();
                wrapper = new QueryWrapper();
                wrapper.eq("COM_BRC_NO", name);
                wrapper.ne("OID", com.getOid());
                DsgApplyCom dupCom = comService.getOne(wrapper, false);
                if (dupCom != null) {
                    wrapper = new QueryWrapper();
                    wrapper.eq("ID_CARD", com.getComBrcNo());
                    if (cusBacklistService.count(wrapper) > 0) {
                        reason = "黑名單";
                    } else {
                        if (com.getComEnName().equalsIgnoreCase(dupCom.getComEnName())) {
                            reason = "ID相同，名字不同";
                        }
                    }
                }
            }
            if (reason == null) {
                //原來生效的資料改為失效
                LambdaUpdateWrapper<DsgApplyCom> updateWrapper = new LambdaUpdateWrapper();
                updateWrapper.eq(DsgApplyCom::getMainNo, bill.getMainNo());
                updateWrapper.eq(DsgApplyCom::getCusStatus, DsgApplyCus.CUS_STATUS_1);
                updateWrapper.set(DsgApplyCom::getCusStatus, DsgApplyCus.CUS_STATUS_3);
                comService.update(new DsgApplyCom(), updateWrapper);

                cusId = com.getOid();
                com.setCusStatus(DsgApplyCus.CUS_STATUS_1);
                comService.updateById(com);
            }
        }

        //更新所有子單關聯的客戶資料
        if (reason == null && cusId != null) {
            LambdaUpdateWrapper<DsgApplyBill> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.eq(DsgApplyBill::getMainNo, bill.getMainNo());
            updateWrapper.set(DsgApplyBill::getCusId, cusId);
            billService.update(new DsgApplyBill(), updateWrapper);
        }

        wrapper = new QueryWrapper();
        wrapper.eq("RESULT_TYPE", DsgApplyResult.RESULT_TYPE_MAN);
        wrapper.eq("RESULT_NAME", name);
        wrapper.eq("APP_NO", bill.getMainNo());
        DsgApplyResult result = resultService.getOne(wrapper);
        if (result == null) {
            result = new DsgApplyResult();
            result.setOid(UUIDGenerator.getUUID());
            result.setResultType(DsgApplyResult.RESULT_TYPE_MAN);
            result.setResultName(name);
            result.setAppNo(bill.getMainNo());
        }
        result.setResultReason(reason);
        result.setResultStatus(reason == null ? DsgApplyResult.RESULT_STATUS_SUCCESS : DsgApplyResult.RESULT_STATUS_FAIL);
        resultService.saveOrUpdate(result);

        LambdaUpdateWrapper<DsgApplyStatus> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(DsgApplyStatus::getAppNo, bill.getAppNo());
        updateWrapper.set(DsgApplyStatus::getIsAuditCus, 1);
        statusService.update(new DsgApplyStatus(), updateWrapper);

        return reason == null;
    }

    @Override
    public List<DsgApplyCus> getCusAndComNoList(String entCode, Integer cusStatus) {
        return baseMapper.getCusAndComNoList(entCode, cusStatus);
    }

    @Override
    public List<DsgApplyCard> getCusAndComCardNoList(String entCode, String cusNo) {
        return baseMapper.getCusAndComCardNoList(entCode, cusNo);
    }
}
